﻿using Basic.FlowApplication.Model;
using Basic.FlowCollect;
using Basic.FlowModel.EventTemplate;
using Basic.FlowRemoteModel;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.AuditLocalEvent.AuditEvent
{
    internal class NodeAuditEvent : IEventHandler<FlowAuditEvent>
    {
        private readonly IEventTemplateCollect _EventTemplate;

        public NodeAuditEvent ( IEventTemplateCollect eventTemplate )
        {
            this._EventTemplate = eventTemplate;
        }

        public void HandleEvent ( FlowAuditEvent data, string eventName )
        {
            if ( data.Item.NodeType == FlowNodeType.结束节点 )
            {
                return;
            }
            data.Log.Items.ForEach(c =>
            {
                FlowNode node = data.Flow.Nodes[c.NodeId];
                FlowEventType evType = this._GetEventType(c.Status);
                if ( node.MsgEvent.TryGetValue(evType, out long evId) )
                {
                    EventDto temp = this._EventTemplate.GetEvent(evId);
                    try
                    {
                        temp.Send(c, data.Log, evType);
                    }
                    catch ( Exception e )
                    {
                        ErrorException error = ErrorException.FormatError(e);
                        error.SaveLog("FlowInter");
                    }
                }
            });
        }
        private FlowEventType _GetEventType ( FlowAuditItemStatus status )
        {
            if ( status == FlowAuditItemStatus.审核进行中 )
            {
                return FlowEventType.节点开始;
            }
            else if ( status == FlowAuditItemStatus.待开始 )
            {
                return FlowEventType.节点创建;
            }
            else
            {
                return FlowEventType.节点结束;
            }
        }
    }
}
